package com.example.sboot.test;

import java.io.File;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLDecoder;

import org.springframework.util.FileCopyUtils;

public class FileDownloadDemo {

	public static void main(String[] args) {
		HttpURLConnection urlConnection = null;
		try {
			String httpUrl = "http://114.116.254.193:18765/ChinatowerFileService/dowloadFile?userId=baijy&fileId=7747DE3053CE48E8908C9B55D9830DE4";
			URL url = new URL(httpUrl);
			urlConnection = (HttpURLConnection) url.openConnection();
			urlConnection.setRequestMethod("GET");
			urlConnection.setRequestProperty("signature","3045022100de7ca411f1d6b003fbd72873fb0082d7329b405ee2c6ddfbf5abf65c3f983257022044982bd0b3349d3f9a9fee90f6d98a24e99879a0c29404567c887205d36a85bd");
			urlConnection.setRequestProperty("timestamp","1644550282478");
			urlConnection.setRequestProperty("nonce","3");
			urlConnection.setRequestProperty("sysCode","CT00012");
			urlConnection.connect();
			InputStream inputStream = urlConnection.getInputStream();
			byte[] bytes = FileCopyUtils.copyToByteArray(inputStream);
			String result = new String(bytes);
			System.out.println("接口返回结果：" + result);
			// 可以用如下的方式判断下载成功或失败；也可以考虑兼容性如果返回结果是json格式则解析json串中的code的值，如果不是000000表示失败，如果不是json格式，返回结果以"下载不成功"、"文件不存在"、"数据权限校验失败"开头也是失败；
			if( result.contains("\"code\":\"000001\"") || 
				result.contains("\"code\":\"000002\"") || 
				result.contains("\"code\":\"000003\"") || 
				result.contains("\"code\":\"000004\"") || 
				result.contains("\"code\":\"000005\"") || 
				result.contains("\"code\":\"000101\"") || 
				result.contains("\"code\":\"999999\"") || 
				result.startsWith("下载不成功") || 
				result.startsWith("文件不存在") || 
				result.startsWith("数据权限校验失败") )
			{
				System.out.println("文件下载失败");
			}
			else
			{
				String disposition = urlConnection.getHeaderField("Content-Disposition");
				String fileName = URLDecoder.decode(disposition.substring(21, disposition.length() - 1), "UTF-8");
				File file = new File("E:/" + fileName);
				FileCopyUtils.copy(bytes, file);
				System.out.println("文件下载成功");
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (urlConnection != null) {
				urlConnection.disconnect();
            }
		}
	}
	
}
